package com.duobaoyu.dby.supply.db.repository.message.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.duobaoyu.dby.supply.core.common.util.DeflaterUtils;
import com.duobaoyu.dby.supply.db.entity.message.SystemLog;
import com.duobaoyu.dby.supply.db.repository.message.SystemLogRepository;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author liyang
 * @version 1.0.0
 * @ClassName SystemLogRepositoryImpl
 * @createTime 17:54:00 2023/10/14
 */
@Repository
@RequiredArgsConstructor
public class SystemLogRepositoryImpl implements SystemLogRepository {

    private final MongoTemplate mongoTemplate;

    @Override
    public boolean save(SystemLog systemLog) {
        SystemLog save = mongoTemplate.save(systemLog);
        return Optional.ofNullable(save).map(SystemLog::getId).map(StringUtils::isNotBlank).orElse(false);
    }

    @Override
    public boolean existsByUniqueKey(String uniqueKey) {
        Query query = new Query(Criteria.where("unique_key").is(uniqueKey));
        return mongoTemplate.exists(query, SystemLog.class);
    }

    @Override
    public SystemLog selectOneById(String systemLogId) {
        SystemLog systemLog = mongoTemplate.findById(systemLogId, SystemLog.class);
        if(Objects.nonNull(systemLog)) {
            systemLog.setParams(DeflaterUtils.unzipString(systemLog.getParams()));
            systemLog.setResponse(DeflaterUtils.unzipString(systemLog.getResponse()));
        }
        return systemLog;
    }

    @Override
    public Page<SystemLog> page(Page<SystemLog> page, Query query) {
        // 12. 总记录数
        long total = mongoTemplate.count(query, SystemLog.class);
        // 8. 查询返回指定字段 (自定义列表)
        //query.fields().include()
        // 10. 分页、排序
        int pageNo = Long.valueOf(page.getCurrent() - 1).intValue();
        int size = Long.valueOf(page.getSize()).intValue();
        query.with(PageRequest.of(pageNo, size, Sort.by(Sort.Order.desc("create_time"))));
        List<SystemLog> mqMessages = mongoTemplate.find(query, SystemLog.class);
        page.setTotal(total);
        mqMessages = mqMessages.stream()
                .peek(systemLog -> systemLog.setParams(DeflaterUtils.unzipString(systemLog.getParams())))
                .peek(systemLog -> systemLog.setResponse(DeflaterUtils.unzipString(systemLog.getResponse())))
                .collect(Collectors.toList());
        page.setRecords(mqMessages);
        return page;
    }
}
